package com.hjb.service.utils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <pre>
 * 统一获取用户IP的代码入口
 * </pre>
 *
 * @author 张克行
 * @since 2016年5月23日
 */
public final class RequestUtil {
	private static Log	log	= LogFactory.getLog(RequestUtil.class);

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	public static HttpSession getSession() {
		HttpServletRequest request = getRequest();
		if (request != null) {
			return request.getSession();
		}
		return null;
	}

	
	public static String getRemoteAddr(HttpServletRequest request) {
		if (request != null) {
			String ip = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			} 
			if (StringUtils.isBlank(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			} 
			if (StringUtils.isBlank(ip)) {
				ip = request.getRemoteAddr();
			} 
			if (!StringUtils.isNotBlank(ip) && ip.contains(",")) {
				String[] ips = ip.split(",");
				ip = ips[ips.length - 1];
			}
			
			if(!ValidUtils.isIP4(ip)){
				ip = "0.0.0.0";
			}
			
			if(StringUtils.isNotBlank(ip))
				return ip;
			else{
				Enumeration<String> keys = request.getHeaderNames();
				while(keys.hasMoreElements()){
					String key = keys.nextElement();
					log.info(key+" = "+request.getHeader(key));
				}
			}
		}
		return "";
	}
	
	public static String getRemoteAddr() {
		HttpServletRequest request = getRequest();
		return getRemoteAddr(request);
	}
}
